<?php
namespace App\Libs\Passport;
use \App\Libs\Base\Constant;
use \App\Libs\Session\Session;
use \App\Libs\Helper\PasswordHelper;
use \App\Libs\Exception\RuntimeException;
class Login extends \App\Libs\Base\Singleton
{
    public function login($token, $password, $captcha = NULL) {
        // 判断类型
        $type = NULL;
        if (preg_match(Constant::MOBILE_REGREX, $token)) {
            $type = 'mobile';
        } else if(preg_match(Constant::EMAIL_REGREX, $token)) {
            $type = 'email';
        } else {
            $type = 'nickname';
        }

        // 获取用户信息
        $info = \App\Libs\User\User::getUserInfo(array($type => $token));
        if ($info === NULL) {
            throw RuntimeException::instance(Constant::ACCOUNT_NOT_EXISTS);
        }

        // 密码判断
        list($salt, $encrypt) = PasswordHelper::encrypt($password, $info['salt']);
        if ($encrypt !== $info['password']) {
            throw RuntimeException::instance(Constant::PASSWORD_ERROR);
        }

        if ($info['is_active'] != 1) {
            throw RuntimeException::instance(Constant::USER_UNACTIVE);
        }

        if ($info['status'] != 1) {
            throw RuntimeException::instance(Constant::USER_FORBIDEN);
        }

        // set session & cookie
        Session::save($info);

        return TRUE;
    }
}
